package com.zb.controller.settings;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zb.common.annotation.Permission;
import com.zb.common.annotation.WriteLog;
import com.zb.common.exception.BusinessException;
import com.zb.common.po.enums.ResponseCode;
import com.zb.common.po.enums.Taskstatus;
import com.zb.common.po.model.Task;
import com.zb.common.po.query.TaskQuery;
import com.zb.common.po.vo.AjaxResponse;
import com.zb.common.utils.PaginationResult;
import com.zb.controller.IndexController;
import com.zb.service.TaskService;

@Controller
@RequestMapping(value = "/task")
public class TaskController {

    Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private TaskService taskService;

    @Permission(code = "task:list")
    @RequestMapping(value = "/task_list.do")
    public String userList() {
        return "page/settings/task_list";
    }

    @Permission(code = "task:list")
    @ResponseBody
    @RequestMapping(value = "/loadTaskList.do")
    public AjaxResponse<PaginationResult<Task>> loadTaskList(TaskQuery query) {
        AjaxResponse<PaginationResult<Task>> response = new AjaxResponse<PaginationResult<Task>>();
        try {
            PaginationResult<Task> result = taskService.findTaskList(query);
            response.setData(result);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("查询任务失败：{}", e);
            response.setResponseCode(ResponseCode.SERVERERROR);
            response.setErrorMsg("查询任务失败");
        }
        return response;
    }

    @Permission(code = "task:add")
    @RequestMapping(value = "/task_2addTask.do")
    public ModelAndView task_2addTask() {
        ModelAndView result = new ModelAndView();
        try {
            result.setViewName("page/settings/task_edit");
            return result;
        } catch (Exception e) {
            logger.error("跳转到任务调度新增页面异常", e);
            return result;
        }
    }

    /**
     * 添加任务
     * 
     * @param task
     * @return
     */
    @Permission(code = "task:add")
    @ResponseBody
    @RequestMapping(value = "/task_add.do")
    @WriteLog(opObject = "任务调度", opDescription = "新增任务：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> task_add(Task task, Integer execution) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            this.taskService.addTask(task, execution == null ? false : true);
            this.taskService.findAllTask();
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存任务失败");
        }
        return response;
    }

    @Permission(code = "task:edit")
    @RequestMapping(value = "/task_2editTask.do")
    public ModelAndView task_2editTask(Integer id) {
        ModelAndView result = new ModelAndView();
        try {
            Task task = this.taskService.findTaskById(id);
            result.addObject("task", task);
            result.setViewName("page/settings/task_edit");
            return result;
        } catch (Exception e) {
            logger.error("跳转到任务调度编辑页面异常", e);
            return result;
        }
    }

    /**
     * 修改任务
     * 
     * @param task
     * @return
     */
    @Permission(code = "task:edit")
    @ResponseBody
    @RequestMapping(value = "/task_edit.do")
    @WriteLog(opObject = "任务调度", opDescription = "新增任务：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> task_edit(Task task, Integer execution) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            this.taskService.findAllTask();
            this.taskService.updateTask(task, execution == null ? false : true);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存任务失败");
        }
        return response;
    }

    /**
     * 暂停任务
     * 
     * @param task
     * @return
     */
    @Permission(code = "task:suspended")
    @ResponseBody
    @RequestMapping(value = "/task_suspended.do")
    @WriteLog(opObject = "任务调度", opDescription = "暂停任务,ID：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> task_suspended(Integer id) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            this.taskService.findAllTask();
            this.taskService.suspendedTask(id);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存任务失败");
        }
        return response;
    }

    @Permission(code = "task:suspended")
    @ResponseBody
    @RequestMapping(value = "/task_enable.do")
    @WriteLog(opObject = "任务调度", opDescription = "启用任务 id：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> task_enable(Integer id) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            this.taskService.findAllTask();
            Task task = new Task();
            task.setId(id);
            task.setTaskStatus(Taskstatus.NORMAL);
            this.taskService.enableTask(id);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存任务失败");
        }
        return response;
    }

    /**
     * 立即执行
     * 
     * @param id
     * @return
     */
    @Permission(code = "task:immediate_execution")
    @ResponseBody
    @RequestMapping(value = "/immediate_execution.do")
    @WriteLog(opObject = "任务调度", opDescription = "立即执行任务：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> immediate_execution(Integer id) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            this.taskService.findAllTask();
            this.taskService.immediateExecutionTask(id);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存任务失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存任务失败");
        }
        return response;
    }

    /**
     * 删除任务
     * 
     * @param session
     * @param ids
     * @return
     */
    @Permission(code = "task:del")
    @ResponseBody
    @RequestMapping(value = "/task_del.do")
    @WriteLog(opObject = "任务调度", opDescription = "删除任务调度：任务ids:[#{#param0}]", paramIndexes = { 1 })
    public AjaxResponse<?> delRole(HttpSession session, Integer[] ids) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            this.taskService.findAllTask();
            this.taskService.deleteTaskBatch(ids);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("删除任务调度失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("删除任务调度失败：{}", e);
            response.setResponseCode(ResponseCode.SERVERERROR);
            response.setErrorMsg("删除任务调度失败");
        }
        return response;
    }
}
